#include"SList.h"
void SListPrint(SNode* phead)
{
    SNode* cur = phead;
    while(cur != NULL)
    {
        printf("%d->", cur->val);
        cur = cur->next;
    }
    printf("NULL\n");
}
SNode* BuySlistNode(SDataType x)
{
    //申请节点
    SNode* NewNode = (SNode*) malloc(sizeof(SNode));
    NewNode->val = x;
    NewNode->next = NULL;
    return NewNode;
}

void SListPushBack(SNode** pphead, SDataType x)
{
    //申请节点
    SNode* NewNode = BuySlistNode(x);
    //分情况 list有数据找尾  刚开始为空不能找尾 改头的指向
    if(*pphead == NULL)
    {
        *pphead = NewNode;//
    }
    else
    {
    //找尾巴
    SNode* tail = *pphead;
    while(tail->next != NULL)
    {
        tail = tail->next;
    }
    tail->next = NewNode;
    }
}

void SListPushFront(SNode** pphead, SDataType x)
{
     //申请节点
    SNode* NewNode = BuySlistNode(x);
    //怎么样都要改头就不存在找的情况
    NewNode->next = *pphead;
    *pphead = NewNode; 
}
void SListPopFront(SNode** pphead)
{
    //没有节点
    assert(*pphead != NULL);
    //保存旧头
    SNode* phead = *pphead;
    //旧头的第二个节点变成新头
    *pphead = phead->next;
    //释放旧头
    free(phead);
}
void SListPopBack(SNode** pphead)
{
    //没有节点
    assert(*pphead != NULL);
    //多个节点  或者只有一个节点
    SNode* tail = *pphead;
    if(tail->next == NULL)
    {
        free(tail);
        *pphead = NULL;
    }
    else
    {
        while(tail->next->next != NULL)
        {
            tail = tail->next;
        }
        free(tail->next);
        tail->next = NULL;
    }
}
SNode* SListFind(SNode* pphead, SDataType x)
{
    SNode* cur = pphead;
    while(cur != NULL)
    {
        if(cur->val == x)
        {
            return cur;
        }
        cur = cur->next; 
    }
    return NULL;
}
void SListInsert(SNode** pphead, SNode*pos, SDataType x)
{
    assert(pos);
    //头插
    if(*pphead == pos)
    {
        //调用头插
        SListPushFront(pphead, x);
    }
    else{
        //找pos前一个
        SNode* prev = *pphead;
        while(prev->next != pos)
        {
            prev =prev->next;
        }
         //申请节点
        SNode* NewNode = BuySlistNode(x);   
        NewNode->next = pos;
        prev->next = NewNode;
    }
}
void SListErase(SNode** pphead, SNode* pos)
{
    assert(pos);
    if(*pphead == pos)
    {
        //调用头插
        SListPopFront(pphead);
    }
    else{
        //找pos前一个
        SNode* prev = *pphead;
        while(prev->next != pos)
        {
            prev =prev->next;
        }
        prev->next = pos->next;
        free(pos);
        pos= NULL;
    }

}
void SListInsertAfter(SNode*pos, SDataType x)
{
    assert(pos);
    SNode* NewNode = BuySlistNode(x);   
    NewNode->next = pos ->next;
    pos->next = NewNode;
}
void SListEraseAfter(SNode* pos)
{
    //保存释放
    assert(pos);
    SNode* after = pos->next;
    pos->next = pos->next->next;
    free(after);
}